package com.thread;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import net.sf.json.JSONObject;

import org.eclipse.swt.widgets.Display;
import org.eclipse.wb.swt.SWTResourceManager;


import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import com.https.HttpHeader;
import com.https.UrlConstants;
import com.ui.MainWindow;
import com.utilities.TimeUtils;

/**
* @ClassName: ConfirmCodeThread
* @Description: TODO
* @author alterhu2020@gmail.com
* @date Feb 15, 2014 9:27:54 PM
* 
*/

public class ConfirmCodeThread extends Thread {

	private MainWindow window;
	private String strTicketType;
	public String inputcode=null;
	
	public ConfirmCodeThread(String strTicketType,MainWindow window) {
		// TODO Auto-generated constructor stub
		this.strTicketType=strTicketType;
		this.window=window;
	}
    @Override
    public void run() {
    	// TODO Auto-generated method stub
    //	super.run();
	    	 Display.getDefault().asyncExec(new Runnable() 
			 { 
				 public void run() 
				 { 
					while(inputcode==null){
						  inputcode= window.text_inputcode.getText().trim();
						  System.out.println("用户已经输入验证码完毕,现在开始校验输入的验证码并提交。。。。。");
						 					  
						  
						  Multimap<String, String> randomcodemap = LinkedListMultimap.create();
					      randomcodemap.put("randCode", inputcode);
					      randomcodemap.put("rand", "sjrand");
					      randomcodemap.put("_json_att", "");
					      System.out.println("检测到已经输入了验证码，现在进行校验验证码操作。。。。。。。。。。。");
					      String check_result;
							try {
								check_result = window.client.postRequest(UrlConstants.URL_CONFIRM_CHECK, randomcodemap, HttpHeader.orderPassCodeCheck(), window.cookies);
							 	
							    JSONObject code_check_json=JSONObject.fromObject(check_result);
							    String data=code_check_json.optString("data");
							    if(data.equals("N")){
							       System.out.println("你输入的验证码错误，我们将重新生成验证码再次校验"); 
							    		//getRandCode(filepath);
							       int codeindex=TimeUtils.randomnumber(100, 10000);
							       String url=UrlConstants.URL_CONFIRM_PASSCODE+codeindex;
							       window.client.getPassCode(url,window.confirm_image, HttpHeader.getPassCode(true), window.cookies);	
							       SWTResourceManager.disposeImages();
								   window.lblNewLabel_refreshcode.setImage(SWTResourceManager.getImage(window.confirm_image));
								   window.lblNewLabel_refreshcode.redraw();
								   window.text_inputcode.setText("");
								   window.logger("成功生成了确认订单的验证码，请先手工输入，暂时不支持自动输入！");
							       inputcode=null;
							    }else if(data.equals("Y")){
							    	window.logger("你输入的验证码正确，我们将提交订单现在。"+inputcode);
							    }else{
							    	window.logger("提交你输入的订单验证码后，从服务器端校验的数据返回错误，你输入的验证码是："+inputcode);
							    }
								
							} catch (KeyManagementException ex) {
								// TODO Auto-generated catch block
								ex.printStackTrace();
							} catch (NoSuchAlgorithmException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					}
				   
			    }});
    	 
    	 try {
    		    window.logger("已经开始提交订单了现在。。。。。");
				String bookmessage=confirmOrder(strTicketType,inputcode,window.longtoken,window.selectedtrain.getYp_info(),window.selectedtrain.getLocation_code(),
						 window.selectedtrain.getOldpassengerstr(),window.selectedtrain.getNewpassengerstr(),window.selectedtrain.getSeate_type_code());
				if(bookmessage=="[]"){
					
				   //org.eclipse.swt.program.Program.launch("http://www.baidu.com");				
					window.logger("订单提交成功，即将停止现在的进程!");
					queryOrderWaitTime();
					org.eclipse.swt.program.Program.launch("https://kyfw.12306.cn/otn/queryOrder/initNoComplete");
					window.logger("恭喜你已经完成了订票的所有操作，赶紧回到网址：https://kyfw.12306.cn/otn/queryOrder/initNoComplete 查看你已经预定的订单吧。");
				}else if(bookmessage.contains("出票失败")){
					
				}else{
					window.logger("出票时候遇到未捕获的异常，导致程序退出。");
				}
				 				 
    	 } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			window.logger("订单确认提交的时候,遇到了异常，现在停止线程成功!");
		}
    	window.isrunthread=false;
		window.isstopped=true;
    	    	 
    }

    
    
	private String confirmOrder(String strTicketType,String randomcode,String longtoken,String yp_info,String location_code,String oldpassenger,String passengerticket,String seat_types) throws KeyManagementException, NoSuchAlgorithmException{
	 Multimap<String, String> params = LinkedListMultimap.create();
		 


   	 params.put("passengerTicketStr", passengerticket);
   	 params.put("oldPassengerStr", oldpassenger);
   	 params.put("randCode", randomcode);
   	 params.put("purpose_codes", strTicketType);
   	 params.put("key_check_isChange", longtoken);
   	 params.put("leftTicketStr", yp_info);
   	 params.put("train_location", location_code);
   	 params.put("_json_att", "");
   	 
   	 String message="";
   	 String datas=window.client.postRequest(UrlConstants.URL_CONFIRMSIMGLE, params, HttpHeader.confirmSingleForQueueAsys(), window.cookies);
   	 if(datas==null){
   		 JSONObject content=JSONObject.fromObject(datas);
   		 message=content.getJSONArray("messages").toString();
   		 
   		 //出票失败的异常
   		 //{"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"errMsg":"出票失败！","submitStatus":false},"messages":[],"validateMessages":{}}
   		 String errormsg=JSONObject.fromObject(datas).optString("errMsg");
   		 window.logger("最后确认提交的订单的时候是否有错误信息如下：\n"+errormsg);
   		 if(errormsg!=null){
   			 window.logger("此次订单提交失败，可能12306的出票遇到了问题，我们将重新进行订票。"+errormsg);
   			 message=errormsg;
   		 }
   		 
   	 }
        System.out.println("确认提交订单："+datas);
        return message;
   	 
	}
	
	public void queryOrderWaitTime() throws KeyManagementException, NoSuchAlgorithmException{
		
		 Multimap<String, String> params = LinkedListMultimap.create();
		 long x=1390611529190l;
		 long y=1390611982323l;
		 long number = x+ (long)(new Random().nextDouble()*(y-x));
   	 params.put("random", String.valueOf(number));
   	 params.put("tourFlag", "dc");
   	 params.put("_json_att", "");
   	 
   	 
   	 String data=window.client.getRequest(UrlConstants.URL_QUERYORDER, params, HttpHeader.queryOrderWaitTime(), window.cookies);
		 System.out.println("data is:"+data);
   	 //parse the data
   	 /*
   	 JSONObject content=JSONObject.fromObject(data);
   	 JSONObject querydata=content.getJSONObject("data");
   	
   	 String queryOrderWaitTimeStatus=querydata.getString("queryOrderWaitTimeStatus");
   	 String count=querydata.getString("count");
   	 String waitTime=querydata.getString("waitTime");
   	 String requestId=querydata.getString("requestId");
   	 String waitCount=querydata.getString("waitCount");
   	 String tourFlag=querydata.getString("tourFlag");
   	 String orderId=querydata.getString("orderId");
   	 */
   	 
	}
	
}
